package mq.config;

import lombok.extern.slf4j.Slf4j;
import mq.dao.mapper.MqMessageAbnormalMapper;
import mq.domain.MqMessageAbnormal;
import mq.service.IMqMailService;
import mq.service.impl.MqMailServiceImpl;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.Optional;

/**
 * @description: 交换机发送给队列的回调函数
 * @author: zk
 * @since: 2022-08-15 15:09
 */

@Slf4j
@Component
public class MyReturnCallback implements RabbitTemplate.ReturnCallback {
    @Resource
    private MqMessageAbnormalMapper mqMessageAbnormalMapper;
    @Resource
    private IMqMailService mqMailService;

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("交换机发送给队列的回调函数:Message={},replyCode={},replyText={},exchange{},routingKey={}",
                message, replyCode, replyText, exchange, routingKey);
        // 回调失败消息入库
        Optional<String> messageId = Optional.ofNullable(message)
                .map(Message::getMessageProperties)
                .map(MessageProperties::getMessageId);

        MqMessageAbnormal mqMessageAbnormal = MqMessageAbnormal.builder()
                //.messageId(messageId.orElseGet(() -> String.valueOf(SnowflakeIdWorker.nextID())))
                //.message(JSON.toJSONString(message))
                //.replyCode(replyCode)
                //.replyText(replyText)
                //.exchange(exchange)
                //.routingKey(routingKey)
                //.status(MqMessageAbnormal.STATUS_FAIL)
                //.type(MqMessageAbnormal.TYPE_QUEUE)
                //.cause(replyText)
                //.createTime(new Date())
                //.updateTime(new Date())
                .build();
        mqMessageAbnormalMapper.insertOrUpdateBatch(Arrays.asList(mqMessageAbnormal));

        // 邮件优化
        messageId.ifPresent(s -> mqMailService.addRecord(s, MqMailServiceImpl.TYPE_RETURN_CALL_BACK));
    }
}
